﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using AiFrame.InterfaceLib.MVVM;
using AiFrameDemo.Contacts.Core.DataStore;
using AiFrameDemo.Contacts.Core.Views;
using AiFrameDemo.Contacts.Lib.Views;
using AiFrameDemo.Lib.Model;

namespace AiFrameDemo.Contacts.Core.ViewModel
{
    public class ContactsListViewModel: IAllocableDataProvider<Contact>
    {
        private readonly IContactsListView _view;
        private Customer _dataSource;
        private Collection<ContactListItem> _contactList;
        private GetAllocableDataFunction<Contact> _allocableDataFunction;

        public ContactsListViewModel(IContactsListView view)
        {
            _view = view;
            _contactList = ContactsFactory.ContactCollectionFactory.CreateBindableContactCollection();
            _view.BindToViewModel(this);
        }

        public Collection<ContactListItem> DataObjectList
        {
            get { return _contactList; }
        }

        public void LoadDataObjects()
        {
            _contactList.Clear();
            IList<Contact> contacts = null;

            if (_allocableDataFunction != null)
            {
                contacts = _allocableDataFunction();
            }
            else
            {
                contacts = DaoFactory.Instance.ContactStore.FindAll();

            }

            foreach (var contact in contacts)
            {
                _contactList.Add(Mapper.ToContactListItem(contact));
            }    
            
        }

        public void SetDataSource(Customer dataSource)
        {
            _dataSource = dataSource;
            
        }

        public void SetAllocableDataFunction(GetAllocableDataFunction<Contact> allocableDataFunction)
        {
            _allocableDataFunction = allocableDataFunction;
        }

        public void UserWantsToAddContact()
        {
            IContactDataView contactDataView = ContactsFactory.ContactsViewFactory.CreateContactDataView();
            ContactDataViewModel viewModel = new ContactDataViewModel(contactDataView);

            contactDataView.SetCaption("Create contact");
            contactDataView.ShowView();
        }
    }
}